package com.mr3chi.horoscopes;

import java.io.IOException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.todddavies.components.progressbar.ProgressWheel;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityNews extends ActionBarActivity{
	
	public static String ARG_LINK 	= "link_info";
	public static String ARG_TITLE 	= "title_info";
	public static String ARG_DATE 	= "date_info";
	public static String ARG_PAGEID = "page_info";
	
	private ProgressWheel 	mLoadBar;
	private RelativeLayout 	mContent;
	
	private TextView tvNewsTitle;
	private TextView tvNewsDate;
	private TextView tvNewsContent;
	
	private NewsLoadingTask task = null;
	
	private String parseTitle;
	private String parseLink;
	private String parseDate;
	private String parsePageId;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_news);
		
		Bundle b = this.getIntent().getExtras();
		parseLink 	= b.getString(ARG_LINK);	
		parseDate 	= b.getString(ARG_DATE);	
		parsePageId = b.getString(ARG_PAGEID);	
		parseTitle 	= b.getString(ARG_TITLE);	
		Log.e("parseLink", parseLink);
		Log.e("parseDate", parseDate);
		Log.e("parsePageId", parsePageId);
		Log.e("parseTitle", parseTitle);
		
		mLoadBar = (ProgressWheel) findViewById(R.id.activity_news_loader);
		mLoadBar.spin();
		mContent = (RelativeLayout) findViewById(R.id.activity_news_info);
		
		tvNewsTitle 	= (TextView) findViewById(R.id.activity_news_title);
		tvNewsTitle.setText(parseTitle);
		tvNewsDate 		= (TextView) findViewById(R.id.activity_news_date);
		tvNewsDate.setText(parseDate);
		tvNewsContent 	= (TextView) findViewById(R.id.activity_news_desc);
		
		parseNewsPage();
		
		AdView adView = (AdView) findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
	}
	
	public void parseNewsPage() {
		if(hasConnection()){
			setLoading(true);
	        task = new NewsLoadingTask(parseLink, parsePageId);
	        task.execute((Void) null);
        } else {
        	Toast.makeText(this, R.string.error_no_intenet_connection, Toast.LENGTH_SHORT).show();
        	setLoading(false);
        	mContent.setVisibility(View.GONE);
        }
	}
	
	public void setLoading(boolean load){
		if(load){
			if(mLoadBar.getVisibility()==View.VISIBLE) return;
			else{
				mLoadBar.setVisibility(View.VISIBLE);
				mContent.setVisibility(View.GONE);
				mLoadBar.spin();
			}
		}else{
			if(mLoadBar.getVisibility()==View.GONE) return;
			else{
				mLoadBar.setVisibility(View.GONE);
				mContent.setVisibility(View.VISIBLE);
				mLoadBar.stopSpinning();
			}
		}
	}
	
	public boolean hasConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);

        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetwork != null && wifiNetwork.isConnected()) {
          return true;
        }

        NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetwork != null && mobileNetwork.isConnected()) {
          return true;
        }

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
          return true;
        }

        return false;
    }
	
	
	public class NewsLoadingTask extends AsyncTask<Void, Void, String>{
		private String link;
		private String pageId;
		
		public NewsLoadingTask(String link, String pageId) {
			this.link = link;
			this.pageId = pageId;
		}
		
		@Override
		protected String doInBackground(Void... params) {
			String rs = "";
			Document doc;
			try {
				
				
				
				if(pageId.equals(WebPage.HUFFINGTONPOST)){
					String reallink = link;
					
					if(!reallink.contains("http://www.huffingtonpost.com")){
						reallink = "http://www.huffingtonpost.com" + link;
					}
					
					URL url = new URL(reallink);
					doc 	= Jsoup.parse(url.openStream(),"UTF-8",reallink);
					
					Log.e("true", "thisi sie");
					Elements nodes = doc.select("div.mdl-content");
					if(nodes != null && nodes.size() > 0){
						rs = nodes.first().html();
					}
				}else{
					Log.e("false	", "false");
				}
				//more page here
				
				
	    		return rs;
	    		
			} catch (IOException e) {
				
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			setLoading(true);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(result == null || result.trim().equals("")){
				Toast.makeText(ActivityNews.this, R.string.error_notarot_here_yet, Toast.LENGTH_SHORT).show();
				setLoading(false);
				mContent.setVisibility(View.GONE);
			}else{
				tvNewsContent.setText(Html.fromHtml(result));
				if(mContent.getVisibility() != View.VISIBLE) mContent.setVisibility(View.VISIBLE);
				setLoading(false);
			}
			
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			setLoading(false);
			task = null;
		}
	}

}
